type FunctionType = (...args: any[]) => void

/**
 * 创建观察者模式
 */
export default function useObserver() {
  let observersList = []

  /**
   * 添加观察者
   */
  const add = (callback: FunctionType) => {
    observersList.push(callback)
  }

  /**
   * 移除观察者
   */
  const remove = (target: FunctionType | string) => {
    if (typeof target === "string") {
      observersList = observersList.filter((observer) => observer.name !== target)
    } else {
      observersList = observersList.filter((observer) => observer !== target)
    }
  }

  /**
   * 通知观察者
   */
  const notify = (data?: unknown) => {
    observersList.forEach((observer) => observer(data))
  }

  return { add, remove, notify }
}
